DIR_LIB = ./lib
DIR_BIN = ./bin
DIR_SRC = ./src

THIRD_LIB_HIREDIS = ./third/hiredis-v0.14.0

v = r
ifeq ($(v), debug)
    TARGET = cworker-d
    CFLAGS = -c -g -Ddebug -O2
else
	TARGET = cworker
    CFLAGS = -c -O3
endif

SOURCES = $(foreach dir, $(shell find $(DIR_SRC) -maxdepth 3 -type d), $(wildcard $(dir)/*.c))
OBJS = $(patsubst %.c, %.o, $(SOURCES))

CFLAGS   += -Wall -fmessage-length=0 -std=gnu99#-pedantic
LDFLAGS  += -lm -pthread -lcurl -lhiredis -Wl,-rpath=$(DIR_LIB)

INC_PATH  = -I./include
INC_PATH += -I$(THIRD_LIB_HIREDIS)
INC_PATH += -I${DIR_SRC}

LIB_PATH  = -L$(DIR_LIB)

all: HIREDIS $(TARGET)

$(TARGET): $(OBJS)
	@test -d $(DIR_BIN) || mkdir $(DIR_BIN)
	@$(CC) $^ -o $(DIR_BIN)/$@ $(LDFLAGS) $(LIB_PATH)
	@echo "Build" $(DIR_BIN)/$@ "successfully."

$(OBJS):%.o: %.c
	$(CC) $(CFLAGS) $< -o $@ $(INC_PATH)

HIREDIS:
	@make -s -C $(THIRD_LIB_HIREDIS)
	@cp $(THIRD_LIB_HIREDIS)/libhiredis.so $(DIR_LIB)/

.PHONY: clean

clean:
	rm -f ${OBJS} ${DIR_BIN}/*
	@make -s -C $(THIRD_LIB_HIREDIS) --no-print-directory clean
